package com.example.admin.controller;

import com.example.admin.bean.User;
import com.example.admin.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    UserService userService;

    @ResponseBody
    @GetMapping("/sql")
    public String queryFromDb(){
        Long aLong = jdbcTemplate.queryForObject("select count(*) from user", Long.class);
        return aLong.toString();
    }

    @ResponseBody
    @GetMapping("/user")
    public User getUserById(@RequestParam("id") Integer id){

        return userService.getUserById(id);
    }

    @GetMapping({"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
//        if (StringUtils.isEmpty(user.getUserName())&&StringUtils.hasLength(user.getPassword())){
        if (!StringUtils.isEmpty(user.getUserName())&&"123456".equals(user.getPassword())){
            //把登陆成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登录成功重定向到index
            return "redirect:/index.html";
        }else {
            model.addAttribute("msg","账号密码错误");
            //回到登录页
            return "login";
        }
    }

    //解决表单重复提交
    @GetMapping("/index.html")
    public String indexPage(HttpSession session,Model model) {
        //是否登录 拦截器
//        Object loginUser = session.getAttribute("loginUser");
//        if (loginUser!=null) {
//            return "index";
//        }else {
//            model.addAttribute("msg","请重新登录误");
//            //回到登录页
//            return "login";
//        }
        return "index";
    }

}
